package com.shenmazong.controller;

import com.shenmazong.dao.TbStudentMapper;
import com.shenmazong.pojo.TbStudent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class StudentController {

    @Autowired
    private TbStudentMapper tbStudentMapper;

    @RequestMapping(value = "/all")
    @ResponseBody
    public Object getAllStudent() {

        List<TbStudent> students = tbStudentMapper.getAllStudent();
        return students;
    }

    @RequestMapping(value = "/test")
    @ResponseBody
    public String test(HttpServletRequest request) {
        String shopid = request.getParameter("shopid");
        System.out.println(shopid);

        return "shopid:"+shopid;
    }

    @RequestMapping(value = "/get")
    @ResponseBody
    public String testGet() {
        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();
        HttpMethod method = HttpMethod.POST;

        // 以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // 准备参数
        MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
        map.add("shopid","get5678");

        //将请求头部和参数合成一个请求
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(map, headers);
        //ResponseEntity<String> response = restTemplate.postForEntity("http://localhost:8080/demo_00_mvc_war/test", requestEntity, String.class);

        ResponseEntity<String> response = restTemplate.exchange("http://localhost:8080/demo_00_mvc_war/test", method, requestEntity, String.class);

        return response.getBody();
    }

    @RequestMapping(value = "/post")
    @ResponseBody
    public String testPost() {
        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();
        HttpMethod method = HttpMethod.POST;

        // 以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // 准备参数
        MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
        map.add("shopid","post1234");

        //将请求头部和参数合成一个请求
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(map, headers);
        ResponseEntity<String> response = restTemplate.postForEntity("http://localhost:8080/demo_00_mvc_war/test", requestEntity, String.class);

        return response.getBody();
    }
}
